//店铺数据模块
import {getShopSellerReq, getGoodsListReq, getShopRateReq} from '@/api/shop'

const state = {
  shopData: {},
  goodsList: [], //商品列表
  rateList: [], //评论列表
}

const getters = {
  navList(state) {
    return state.goodsList.map(v => v.name)
  },
  //筛选
  goodRateList(state) {
    return state.rateList.filter(v => {
      return v.score > 3
    })
  },
  badRateList(state) {
    return state.rateList.filter(v => {
      return v.score <= 3
    })
  },
  // 筛选出 count>0食品
  filterFoodsList(state) {
    let tem = []
    state.goodsList.forEach(v => {
      v.foods.forEach(v2 => {
        if (v2.count > 0) {
          tem.push(v2)
        }
      })
    })
    return tem
  },
  // 计算选中总数量
  filterTotalCount(state, getters) {
    return getters.filterFoodsList.reduce((total, cur) => {
      return total + cur.count
    }, 0)
  },
  // 计算选中总价格
  filterTotalMoney(state, getters) {
    return getters.filterFoodsList.reduce((total, cur) => {
      return total + cur.count * cur.price
    }, 0)
  },
}

const mutations = {
  SET_SHOPINFO(state, data) {
    state.shopData = data
  },
  SET_GOODSLIST(state, data) {
    state.goodsList = data
  },
  SET_RATE(state, data) {
    state.rateList = data
  },
}

const actions = {
  //获取店铺数据
  A_getShopInfo({commit}) {
    return new Promise(async resolve => {
      let res = await getShopSellerReq()
      //解构数据
      let {data} = res.data
      //数据赋值
      commit('SET_SHOPINFO', data)
      resolve()
    })
  },
  // 获取商品数据
  A_getgoodsList({commit}) {
    return new Promise(async resolve => {
      let res = await getGoodsListReq()
      //解构数据
      let {data, code} = res.data
      // 判断
      if (code === 0) {
        // 处理数据
        data.forEach(v => {
          v.foods.forEach(v2 => {
            //给每个食品新增一个count字段
            v2.count = 0
          })
        })
        //数据赋值
        commit('SET_GOODSLIST', data)
        resolve()
      }
    })
  },

  //获取评价
  A_getShopRate({commit}) {
    return new Promise(async resolve => {
      let res = await getShopRateReq()
      let {errno, data} = res.data
      if (errno === 0) {
        commit('SET_RATE', data)
        resolve()
      }
    })
  },
}

export default {
  namespaced: true,
  getters,
  state,
  mutations,
  actions,
}
